<template>
  <div class="con-data">
    <ul>
      <li>
        <label
          ><span>昵称：</span><input type="text" v-model="nickname"
        /></label>
      </li>
      <li><span>用户名：</span>{{ info.username }}</li>
      <li><button @click="upNickname">保存</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { updateNickApi } from "../../../api";
export default {
  name: "UpdateDate",
  data() {
    return {
      nickname: "",
    };
  },
  computed: {
    ...mapState("user", { info: "info" }),
  },
  watch: {
    info: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        if (newValue.nickname === (oldValue ? oldValue.nickname : "")) return;
        this.nickname = newValue.nickname;
      },
    },
  },
  methods: {
    upNickname() {
      if (this.nickname === this.info.nextTick) return;
      updateNickApi(
        (response) => {
          console.log(response.data);
          if (response.data.status === 1) {
            // 修改成功后更新数据
            this.$store.dispatch("user/getInfo");
            this.$bus.$emit("showTips", "昵称修改成功！");
            return;
          }
          this.$bus.$emit("showTips", "昵称修改失败！");
        },
        (err) => {
          this.$bus.$emit("showTips", "出错了，请检查以下网络吧！");
          console.log(err);
        },
        {
          nickname: this.nickname,
        }
      );
    },
  },
};
</script>

<style lang="stylus" scoped>
.con-data {
  width: 80%;
  color: #aaa;
  font-size: 14px;

  ul {
    padding-top: 20px;
    line-height: 50px;
  }

  li>span:first-child, label>span:first-child {
    display: inline-block;
    width: 90px;
    vertical-align: middle;
  }

  input {
    width: 180px;
    height: 22px;
    padding: 0 6px;
    border: 1px solid #999;
    vertical-align: middle;
  }

  button {
    padding: 6px 20px;
    border: none;
    margin-left: 120px;
    border-radius: 4px;
    font-size: 14px;
    background-color: #fe4d1b;
    color: #fff;
  }
}
</style>